<template>
	<div v-loading="loading">
		<div class="coupon-card">
			<el-row :gutter="10">
				<el-col :xs="12" :sm="8" :md="8" v-for="(item, index) in cardData_1" :key="index">
					<div class="app-main-content-box"><OnePointCard :data="item" /></div>
				</el-col>
			</el-row>
		</div>
		<div class="form">
			<el-form :inline="true" :model="formData" class="demo-form-inline" label-width="80px" ref="formData" :rules="rules">
				<el-row>
					<el-col :span="showMore ? 8 : 7">
						<el-form-item label="核销时间" size="small" prop="date">
							<el-date-picker
								v-model="formData.date"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="['00:00:00', '23:59:59']"
								type="datetimerange"
								range-separator="~"
								value-format="yyyy-MM-dd HH:mm:ss"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="showMore ? 8 : 6">
						<el-form-item label="核销业务" size="small" prop="bizCode">
							<el-select v-model="formData.bizCode" filterable placeholder="请选择" style="width: 400px">
								<el-option label="全部" value="" />
								<el-option v-for="(item, index) in manageBizCodeOptions" :key="index" :label="item.label" :value="item.key" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="showMore ? 8 : 6">
						<el-form-item label="订单编号" size="small" prop="orderNo"><el-input v-model="formData.orderNo" placeholder="订单编号"></el-input></el-form-item>
					</el-col>
					<el-col :span="5" v-if="!showMore">
						<el-button type="primary" round size="small" @click="search()">查询</el-button>
						<el-button type="" round size="small" @click="resetForm('formData')">重置</el-button>
						<el-button type="" round size="small" @click="exprotExcel()">导出</el-button>
						<el-button type="text" size="small" @click="showMore = true">展开</el-button>
					</el-col>
				</el-row>
				<div v-show="showMore">
					<el-row>
						<!-- <el-col :span="8">
              <el-form-item label="核销终端" size="small" prop="endpoint">
                <el-input
                  v-model="formData.endpoint"
                  placeholder="核销终端"
                ></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="核销门店" size="small" prop="shopName">
                <el-input
                  v-model="formData.md"
                  placeholder="核销门店名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核销方" size="small" prop="merchant">
                <el-cascader
                  v-model="formData.merchant"
                  :options="
                    [{ id: '', name: '全部' }].concat(allAuthMchOptions)
                  "
                  :props="{
                    checkStrictly: true,
                    value: 'id',
                    label: 'name',
                    children: 'shops',
                  }"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核销来源" size="small" prop="sourceCode">
                <el-select
                  v-model="formData.sourceCode"
                  filterable
                  placeholder="请选择"
                  style="width: 400px"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="(item, index) in sourceCodeOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="流水号" size="small" prop="serialNo">
                <el-input
                  v-model="formData.serialNo"
                  placeholder="交易流水号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="卡类型" size="small" prop="cardType">
                <el-select
                  v-model="formData.cardType"
                  filterable
                  placeholder="请选择"
                  style="width: 400px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="次卡" value="times" />
                  <el-option label="礼品卡" value="gift" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="卡名称" size="small" prop="cardName">
                <el-input
                  v-model="formData.cardName"
                  placeholder="卡名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="卡号" size="small" prop="cardNo">
                <el-input
                  v-model="formData.cardNo"
                  placeholder="卡号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!isDetail">
              <el-form-item label="顾客号码" size="small" prop="customerPhone">
                <el-input
                  v-model="formData.customerPhone"
                  placeholder="顾客号码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!isDetail">
              <el-form-item label="顾客" size="small" prop="customerName">
                <el-input
                  v-model="formData.customerName"
                  placeholder="顾客昵称/姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核销号码" size="small" prop="operatorPhone">
                <el-input
                  v-model="formData.operatorPhone"
                  placeholder="核销人员手机号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核销人员" size="small" prop="operatorName">
                <el-input
                  v-model="formData.operatorName"
                  placeholder="核销人员昵称/姓名"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-button type="primary" round size="small" @click="search()"
                >查询</el-button
              >
              <el-button
                type=""
                round
                size="small"
                @click="resetForm('formData')"
                >重置</el-button
              >
              <el-button type="" round size="small" @click="exprotExcel()"
                >导出</el-button
              >
              <el-button type="text" size="small" @click="showMore = false"
                >收起</el-button
              >
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <div class="table-container app-main-content-box">
      <el-table
        :data="list"
        size="small"
        stripe
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="createTime"
          label="核销时间"
          fixed="left"
          width="135"
        />
        <el-table-column prop="cardName" label="卡名称" />
        <el-table-column prop="cardCode" label="卡号" width="155">
          <template slot-scope="scope">
            {{ scope.row.cardNo || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="serialNo" label="流水号" width="155">
          <template slot-scope="scope">
            {{ scope.row.serialNo || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="订单编号" width="155">
          <template slot-scope="scope">
            <div
              v-if="scope.row.orderNo"
              @click="toOrderDetai(scope.row)"
              class="to-detail"
            >
              {{ scope.row.orderNo }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="核销金额（元）/ 核销次数（次）"  width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.cardType === 'times'">
				{{scope.row.verifyAmount || 0}}
			</span>
			<span v-else>{{(scope.row.verifyAmount / 100).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="couponType" label="类型">
          <template slot-scope="scope">
            <span>{{ cardTypeOptions[scope.row.cardType] || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="核销来源">
          <template slot-scope="scope">
            <span>{{
              sourceCodeKeyOptions[scope.row.sourceCode] || "--"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="shopName" label="核销门店" width="150" />
        <!-- <el-table-column prop="endpoint" label="核销终端">
          <template slot-scope="scope">
            <span>{{ scope.row.endpointName || "--" }}</span>
          </template>
        </el-table-column> -->
				<el-table-column label="核销业务">
					<template slot-scope="scope">
						<span>{{ bizCodeKeyOptions[scope.row.bizCode] || '--' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="customerName" label="顾客" fixed="right" width="140">
					<template slot-scope="scope">
						{{ scope.row.customerPhone ? `${scope.row.customerName}(${scope.row.customerPhone})` : `${scope.row.customerName || '--'}` }}
					</template>
				</el-table-column>
				<el-table-column label="核销人员" fixed="right" width="180">
					<template slot-scope="scope">
						{{ scope.row.operatorPhone ? `${scope.row.operatorName}(${scope.row.operatorPhone})` : `${scope.row.operatorName || '--'}` }}
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig" @sizeschange="sizesChange" @pagechange="pageChange"></pagination-direction>
		</div>
	</div>
</template>

<script>
import { getCardVerify, getCardVerifyCount, exportCardWriteOff } from '@/api/coupon';
import { mapGetters } from 'vuex';
import OnePointCard from './OnePointCard';
import { authMerchants } from '@/views/cardsAndOffer/api/mch';

export default {
  components: {
    OnePointCard,
  },
  props: {
    isDetail: {
      type: Boolean,
      default: false,
    },
    vipDetail: {
      type: Object,
    },
  },
  computed: {
    ...mapGetters([
      "manageShopList",
      "manageBizCodeOptions",
      "bizCodeKeyOptions",
      "sourceCodeOptions",
      "sourceCodeKeyOptions",
      "userInfo",
    ]),
  },
  data() {
    const validatorDate = (rule, value, callback) => {
      if (value && value.length) {
        callback();
      } else {
        callback(new Error("请选择时间"));
      }
    };
    return {
      activeTab: 1,
      rules: {
        date: [
          {
            validator: validatorDate,
            trigger: ["blur", "change"],
          },
        ],
      },
      paginationConfig: {
        // 分页配置
        direction: "center", // 分页位置
        layout: "total, sizes, prev, pager, next, jumper", // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 10,
        page: 1, // 页数-默认1
        pageSize: 10, // 每页条数-默认10
      },
      cardTypeOptions: {
        times: "次卡",
        gift: "礼品卡",
      },
      verifyWayTableOptions: {
        1: "线下核销",
        2: "助手小程序核销",
        3: "线上订单支付核销 ",
        4: "POS核销",
        5: "商户app",
      },
      formData: {
        date: [
          this.$momentMini().subtract(6, "days").format("YYYY-MM-DD") +
            " 00:00:00",
          this.$momentMini().format("YYYY-MM-DD") + " 23:59:59",
        ],
        bizCode: "",
        orderNo: "",
        // endpoint: "",
        shopName: "",
        merchant: "",
        sourceCode: "",
        cardType: "",
        cardName: "",
        customerPhone: "",
        customerName: "",
        operatorPhone: "",
        operatorName: "",
        serialNo: "",
        cardCode: "",
      },
      // 状态
      loading: false,
      // 数据
      cardData_1: [],
      list: [],
      showMore: false,
      allAuthMchOptions: [],
    };
  },
  mounted() {
    this.getAuthMerchants();
    this.fetchData();
  },
  methods: {
    /**
     *  获取数据
     */
    // 获取数据
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      let { isDetail, formData } = this;
      let { merchant } = formData;
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const params = Object.assign({}, formData);
          isDetail ? (params.customerId = this.vipDetail?.customer?.id) : "";
          params.start = formData.date[0];
          params.end = formData.date[1];
          if (merchant.length > 1) {
            params.merchant = merchant[0];
            params.shopId = merchant[1];
          } else if (merchant.length == 1) {
            params.merchant = merchant[0];
          }
          delete params.date;
          getCardVerifyCount(params).then((res) => {
            if (res.code == 0) {
              this.cardData_1 = [
                ["礼品卡/笔", res.data.giftTotal || 0],
                ["礼品卡/核销金额（元）", (res.data.giftVerifyAmount/100).toFixed(2) || 0],
                ["次卡/笔", res.data.timesTotal || 0],
                ["次卡/次", res.data.timesVerifyAmount || 0],
              ];
            }
          });
          params.pageSize = pageSize;
          params.page = page;
          getCardVerify(params).then((res) => {
            if (res.code == 0) {
              this.list = res.data.list;
              this.paginationConfig.total = res.data.total;
              this.paginationConfig.page = res.data.pageNum;
            }
          });
        }
      });
    },

		// 分页sizes改变
		sizesChange() {
			this.fetchData();
		},

		// 分页page改变
		pageChange() {
			this.fetchData();
		},
		getAuthMerchants() {
			let { id } = this.userInfo.business;
			let { isAdmin, shopId } = this.userInfo;
			return new Promise(resolve => {
				authMerchants({ belongMerchant: id, queryType: 0 })
					.then(res => {
						if (!isAdmin) {
							// 删除不属于本商户的门店
							for (let i = 0; i < res.data.length; i++) {
								if (res.data[i].id == id) {
									let shops = res.data[i].shops;
									for (let k = 0; k < shops.length; k++) {
										if (shops[k].id != shopId) {
											delete shops[k];
										}
									}
								}
							}
							this.allAuthMchOptions = res.data;
						} else {
							this.allAuthMchOptions = res.data;
						}
					})
					.finally(() => {
						resolve();
					});
			});
		},
		search() {
			this.paginationConfig.page = 1;
			this.fetchData();
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.paginationConfig.page = 1;
			this.paginationConfig.pageSize = 10;
			this.fetchData();
		},
		exprotExcel(page = this.paginationConfig.page, pageSize = this.paginationConfig.pageSize) {
			let { isDetail, formData } = this;
			let { merchant, date } = formData;
			const params = Object.assign({}, formData);
			isDetail ? (params.customerId = this.vipDetail?.customer?.id) : '';
			params.start = date ? formData.date[0] : '';
			params.end = date ? formData.date[1] : '';
			if (merchant.length > 1) {
				params.merchant = merchant[0];
				params.shopId = merchant[1];
			} else if (merchant.length == 1) {
				params.merchant = merchant[0];
			}
			delete params.date;
			params.pageSize = pageSize;
			params.page = page;
			exportCardWriteOff(params).then(res => {
				this.$alert('数据导出中，请稍后到数据下载中心进行下载', '提示', {
					confirmButtonText: '确定',
					center: true,
					type: 'success',
					callback: action => {}
				});
			});
		},
		toOrderDetai(row) {
			let { bizCode, orderNo } = row;
			let routeData;
			// 1 商城订单 2 预定订单 3 积分兑换订单 4 点餐订单 其他 预约订单
			// 9013 商城订单 9004 预定订单 9011积分商城  9005 点餐订单 9014 预约订单  9012码牌支付  9056 优惠券核销 9070 扫码领取优惠券
			let pathPar = {
				9013: '/wxaMallModule/orderManage',
				9004: '/bookingModule/orderRecord',
				9011: '/statement/points-mall-record',
				9005: '/wcyModule/orderRecord',
				9014: '/wxaReservationModule/orderManage'
			};
			let path = pathPar[bizCode];
			if (!path) {
				routeData = this.$router.resolve({
					path: '/payCenterDir/IncomeHis',
					query: { orderNo, from: 'cancelTable' }
				});
			} else {
				routeData = this.$router.resolve({
					path,
					query: { orderNo, from: 'cancelTable' }
				});
			}
			window.open(routeData.href, '_blank');
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.coupon-card {
	.app-main-content-box {
		margin-bottom: 10px;
	}
}
.form {
	background-color: #fff;
	padding: 20px 30px 0;
	/deep/.el-select,
	.el-date-editor--datetimerange {
		width: 100% !important;
	}
	.el-form-item {
		width: calc(100% - 20px) !important;
		display: flex;
		/deep/.el-form-item__content {
			flex: 1;
		}
	}
}
.to-detail {
	cursor: pointer;
	color: #f0b73d;
}
</style>
